<template>
  <div
    :class="avatarClasses"
    :style="avatarStyles"
    @click="handleClick"
  >
    <!-- 头像图片 -->
    <van-image
      v-if="src || defaultSrc"
      :src="currentSrc"
      :alt="alt"
      :fit="fit"
      :round="round"
      :width="size"
      :height="size"
      :loading-icon="loadingIcon"
      :error-icon="errorIcon"
      :show-loading="showLoading"
      :show-error="showError"
      @load="handleLoad"
      @error="handleError"
      @click="handleImageClick"
    />
    
    <!-- 文字头像 -->
    <div v-else-if="name" class="user-avatar__text">
      {{ avatarText }}
    </div>
    
    <!-- 默认图标 -->
    <van-icon v-else name="user-o" :size="iconSize" />

    <!-- 状态指示器 -->
    <div
      v-if="showStatus && status"
      :class="statusClasses"
      :style="statusStyles"
    >
      <van-icon v-if="statusIcon" :name="statusIcon" :size="statusIconSize" />
    </div>

    <!-- 徽章 -->
    <van-badge
      v-if="badge !== null && badge !== undefined"
      :content="badge"
      :dot="badgeDot"
      :max="badgeMax"
      :color="badgeColor"
      :position="badgePosition"
      :offset="badgeOffset"
    />

    <!-- 编辑按钮 -->
    <div
      v-if="editable"
      class="user-avatar__edit"
      @click.stop="handleEdit"
    >
      <van-icon name="edit" :size="editIconSize" />
    </div>
  </div>
</template>

<script>
import { computed, ref, defineComponent } from 'vue'

export default defineComponent({
  name: 'UserAvatar',
  props: {
    /**
     * 头像图片地址
     */
    src: {
      type: String,
      default: ''
    },
    /**
     * 默认头像图片地址
     */
    defaultSrc: {
      type: String,
      default: ''
    },
    /**
     * 用户名称（用于生成文字头像）
     */
    name: {
      type: String,
      default: ''
    },
    /**
     * 图片描述
     */
    alt: {
      type: String,
      default: '用户头像'
    },
    /**
     * 头像尺寸
     */
    size: {
      type: [Number, String],
      default: 40
    },
    /**
     * 头像形状
     */
    shape: {
      type: String,
      default: 'round',
      validator: (value) => ['round', 'square'].includes(value)
    },
    /**
     * 是否圆形
     */
    round: {
      type: Boolean,
      default: true
    },
    /**
     * 图片填充模式
     */
    fit: {
      type: String,
      default: 'cover',
      validator: (value) => ['contain', 'cover', 'fill', 'none', 'scale-down'].includes(value)
    },
    /**
     * 加载图标
     */
    loadingIcon: {
      type: String,
      default: 'photo-o'
    },
    /**
     * 错误图标
     */
    errorIcon: {
      type: String,
      default: 'photo-fail'
    },
    /**
     * 是否显示加载状态
     */
    showLoading: {
      type: Boolean,
      default: true
    },
    /**
     * 是否显示错误状态
     */
    showError: {
      type: Boolean,
      default: true
    },
    /**
     * 用户状态
     */
    status: {
      type: String,
      default: '',
      validator: (value) => ['', 'online', 'offline', 'busy', 'away'].includes(value)
    },
    /**
     * 是否显示状态指示器
     */
    showStatus: {
      type: Boolean,
      default: false
    },
    /**
     * 状态图标
     */
    statusIcon: {
      type: String,
      default: ''
    },
    /**
     * 徽章内容
     */
    badge: {
      type: [String, Number],
      default: null
    },
    /**
     * 是否显示小红点
     */
    badgeDot: {
      type: Boolean,
      default: false
    },
    /**
     * 徽章最大值
     */
    badgeMax: {
      type: Number,
      default: 99
    },
    /**
     * 徽章颜色
     */
    badgeColor: {
      type: String,
      default: '#ee0a24'
    },
    /**
     * 徽章位置
     */
    badgePosition: {
      type: String,
      default: 'top-right',
      validator: (value) => ['top-left', 'top-right', 'bottom-left', 'bottom-right'].includes(value)
    },
    /**
     * 徽章偏移量
     */
    badgeOffset: {
      type: Array,
      default: () => [0, 0]
    },
    /**
     * 是否可编辑
     */
    editable: {
      type: Boolean,
      default: false
    },
    /**
     * 是否可点击
     */
    clickable: {
      type: Boolean,
      default: false
    },
    /**
     * 是否禁用
     */
    disabled: {
      type: Boolean,
      default: false
    },
    /**
     * 背景颜色
     */
    backgroundColor: {
      type: String,
      default: ''
    },
    /**
     * 文字颜色
     */
    textColor: {
      type: String,
      default: ''
    },
    /**
     * 边框颜色
     */
    borderColor: {
      type: String,
      default: ''
    },
    /**
     * 边框宽度
     */
    borderWidth: {
      type: [Number, String],
      default: 0
    }
  },
  emits: ['click', 'load', 'error', 'edit'],
  setup(props, { emit }) {
    const imageLoaded = ref(false)
    const imageError = ref(false)

    /**
     * 当前头像地址
     */
    const currentSrc = computed(() => {
      if (imageError.value && props.defaultSrc) {
        return props.defaultSrc
      }
      return props.src || props.defaultSrc
    })

    /**
     * 头像文字
     */
    const avatarText = computed(() => {
      if (!props.name) return ''
      
      // 取名称的第一个字符，如果是中文取最后一个字符
      const name = props.name.trim()
      if (/[\u4e00-\u9fa5]/.test(name)) {
        return name.slice(-1)
      }
      return name.charAt(0).toUpperCase()
    })

    /**
     * 头像样式类
     */
    const avatarClasses = computed(() => {
      const classes = [
        'user-avatar',
        `user-avatar--${props.shape}`
      ]

      if (props.clickable) {
        classes.push('user-avatar--clickable')
      }

      if (props.disabled) {
        classes.push('user-avatar--disabled')
      }

      if (props.editable) {
        classes.push('user-avatar--editable')
      }

      return classes
    })

    /**
     * 头像内联样式
     */
    const avatarStyles = computed(() => {
      const styles = {
        width: typeof props.size === 'number' ? `${props.size}px` : props.size,
        height: typeof props.size === 'number' ? `${props.size}px` : props.size
      }

      if (props.backgroundColor) {
        styles.backgroundColor = props.backgroundColor
      }

      if (props.borderColor && props.borderWidth) {
        styles.border = `${typeof props.borderWidth === 'number' ? `${props.borderWidth}px` : props.borderWidth} solid ${props.borderColor}`
      }

      return styles
    })

    /**
     * 状态指示器样式类
     */
    const statusClasses = computed(() => {
      const classes = ['user-avatar__status']
      
      if (props.status) {
        classes.push(`user-avatar__status--${props.status}`)
      }

      return classes
    })

    /**
     * 状态指示器内联样式
     */
    const statusStyles = computed(() => {
      const size = typeof props.size === 'number' ? props.size : parseInt(props.size)
      const statusSize = Math.max(8, size * 0.2)
      
      return {
        width: `${statusSize}px`,
        height: `${statusSize}px`,
        right: `${size * 0.05}px`,
        bottom: `${size * 0.05}px`
      }
    })

    /**
     * 图标尺寸
     */
    const iconSize = computed(() => {
      const size = typeof props.size === 'number' ? props.size : parseInt(props.size)
      return Math.max(16, size * 0.4)
    })

    /**
     * 状态图标尺寸
     */
    const statusIconSize = computed(() => {
      const size = typeof props.size === 'number' ? props.size : parseInt(props.size)
      return Math.max(6, size * 0.15)
    })

    /**
     * 编辑图标尺寸
     */
    const editIconSize = computed(() => {
      const size = typeof props.size === 'number' ? props.size : parseInt(props.size)
      return Math.max(12, size * 0.3)
    })

    /**
     * 点击处理
     */
    const handleClick = (event) => {
      if (!props.disabled && props.clickable) {
        emit('click', event)
      }
    }

    /**
     * 图片点击处理
     */
    const handleImageClick = (event) => {
      if (!props.disabled && props.clickable) {
        emit('click', event)
      }
    }

    /**
     * 图片加载成功处理
     */
    const handleLoad = (event) => {
      imageLoaded.value = true
      imageError.value = false
      emit('load', event)
    }

    /**
     * 图片加载失败处理
     */
    const handleError = (event) => {
      imageLoaded.value = false
      imageError.value = true
      emit('error', event)
    }

    /**
     * 编辑处理
     */
    const handleEdit = (event) => {
      if (!props.disabled) {
        emit('edit', event)
      }
    }

    return {
      imageLoaded,
      imageError,
      currentSrc,
      avatarText,
      avatarClasses,
      avatarStyles,
      statusClasses,
      statusStyles,
      iconSize,
      statusIconSize,
      editIconSize,
      handleClick,
      handleImageClick,
      handleLoad,
      handleError,
      handleEdit
    }
  }
})
</script>

<style lang="scss" scoped>
.user-avatar {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #f7f8fa;
  color: #646566;
  font-weight: 500;
  overflow: hidden;
  user-select: none;

  &--round {
    border-radius: 50%;
  }

  &--square {
    border-radius: 4px;
  }

  &--clickable {
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      opacity: 0.8;
      transform: scale(1.05);
    }

    &:active {
      transform: scale(0.95);
    }
  }

  &--disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  &--editable {
    &:hover {
      .user-avatar__edit {
        opacity: 1;
      }
    }
  }

  &__text {
    font-size: 14px;
    line-height: 1;
    color: inherit;
  }

  &__status {
    position: absolute;
    border: 2px solid #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;

    &--online {
      background-color: #52c41a;
    }

    &--offline {
      background-color: #d9d9d9;
    }

    &--busy {
      background-color: #ff4d4f;
    }

    &--away {
      background-color: #faad14;
    }
  }

  &__edit {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    opacity: 0;
    transition: opacity 0.3s ease;
    cursor: pointer;
    border-radius: inherit;

    &:hover {
      opacity: 1;
    }
  }

  // 尺寸变体
  &--large {
    .user-avatar__text {
      font-size: 18px;
    }
  }

  &--small {
    .user-avatar__text {
      font-size: 12px;
    }
  }

  &--mini {
    .user-avatar__text {
      font-size: 10px;
    }
  }
}

// 全局样式覆盖
:global(.van-image) {
  border-radius: inherit;
}

:global(.van-badge) {
  .van-badge__wrapper {
    border-radius: inherit;
  }
}
</style>